<template>
  <div class="ratings">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="我的评分"
      left-arrow
      @click-left="$router.back()"
      fixed
    />

    <div class="content">
      <van-empty v-if="loading" description="加载中...">
        <template #image>
          <van-loading type="spinner" size="36" />
        </template>
      </van-empty>

      <van-empty
        v-else-if="ratingList.length === 0"
        description="暂无评分记录"
      />

      <template v-else>
        <!-- 评分记录列表 -->
        <van-cell-group
          inset
          v-for="(group, date) in groupedRatingList"
          :key="date"
          :title="formatDate(date)"
        >
          <van-swipe-cell
            v-for="item in group"
            :key="item.id"
            :before-close="beforeClose"
          >
            <van-cell @click="navigateToDetail(item)">
              <template #icon>
                <van-image
                  width="50"
                  height="50"
                  fit="cover"
                  :src="item.image || 'https://img.yzcdn.cn/vant/cat.jpeg'"
                  style="margin-right: 10px; border-radius: 4px"
                />
              </template>
              <template #title>
                <div class="item-title">
                  <span>{{ item.name }}</span>
                  <div class="item-rating">
                    <van-rate
                      v-model="item.score"
                      readonly
                      :size="16"
                      color="#ffd21e"
                      void-icon="star"
                      void-color="#eee"
                    />
                    <span class="score-text">{{ item.score.toFixed(1) }}</span>
                  </div>
                </div>
              </template>
              <template #label>
                <div class="item-type">{{ getItemTypeName(item.type) }}</div>
                <div class="item-comment" v-if="item.comment">
                  {{ item.comment }}
                </div>
                <div class="rate-time">{{ formatTime(item.rateTime) }}</div>
              </template>
            </van-cell>

            <template #right>
              <van-button
                square
                type="primary"
                text="编辑"
                class="edit-button"
                @click="handleEditRating(item)"
              />
              <van-button
                square
                type="danger"
                text="删除"
                class="delete-button"
                @click="handleDeleteRating(item.id)"
              />
            </template>
          </van-swipe-cell>
        </van-cell-group>

        <!-- 加载更多 -->
        <div class="load-more" v-if="hasMore">
          <van-button plain type="primary" size="small" @click="loadMore"
            >加载更多</van-button
          >
        </div>
      </template>
    </div>

    <!-- 编辑评分弹窗 -->
    <van-dialog
      v-model:show="showEditDialog"
      title="修改评分"
      show-cancel-button
      @confirm="confirmEditRating"
    >
      <div class="edit-rating-form">
        <div class="edit-item-info">
          <van-image
            width="60"
            height="60"
            fit="cover"
            :src="currentRating?.image || 'https://img.yzcdn.cn/vant/cat.jpeg'"
          />
          <div class="edit-item-name">{{ currentRating?.name }}</div>
        </div>
        <div class="edit-score">
          <span class="edit-label">评分：</span>
          <van-rate
            v-model="editForm.score"
            :size="24"
            color="#ffd21e"
            void-icon="star"
            void-color="#eee"
            allow-half
          />
          <span class="edit-score-text">{{ editForm.score.toFixed(1) }}</span>
        </div>
        <div class="edit-comment">
          <van-field
            v-model="editForm.comment"
            label="评论"
            type="textarea"
            placeholder="请输入评论内容"
            rows="3"
            maxlength="200"
            show-word-limit
          />
        </div>
      </div>
    </van-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import { showToast, showConfirmDialog } from "vant";
import { useUserStore } from "../../stores/userStore";

// 模拟API函数
const getUserRatings = async (userId, page, size) => {
  // 这里替换为实际的API调用
  console.log(`获取用户${userId}的评分记录, 页码:${page}, 大小:${size}`);

  // 模拟数据
  return {
    code: 200,
    data: {
      records: [
        {
          id: 1,
          name: "健康沙拉",
          type: "recipe",
          targetId: 1,
          score: 4.5,
          comment: "非常健康美味的沙拉，搭配得很好",
          rateTime: Date.now() - 1000 * 60 * 60 * 2,
          image: "https://img.yzcdn.cn/vant/cat.jpeg",
        },
        {
          id: 2,
          name: "西兰花",
          type: "food",
          targetId: 1,
          score: 5,
          comment: "新鲜营养，非常好",
          rateTime: Date.now() - 1000 * 60 * 60 * 24,
          image: "https://img.yzcdn.cn/vant/cat.jpeg",
        },
        {
          id: 3,
          name: "蒸鲈鱼",
          type: "recipe",
          targetId: 3,
          score: 4,
          comment: "做法简单，味道不错",
          rateTime: Date.now() - 1000 * 60 * 60 * 24 * 2,
          image: "https://img.yzcdn.cn/vant/cat.jpeg",
        },
      ],
      total: 6,
      size: size,
      current: page,
    },
  };
};

const updateRating = async (ratingId, data, userId) => {
  // 这里替换为实际的API调用
  console.log(`更新用户${userId}的评分:${ratingId}`, data);

  // 模拟成功响应
  return { code: 200, message: "更新评分成功" };
};

const deleteRating = async (ratingId, userId) => {
  // 这里替换为实际的API调用
  console.log(`删除用户${userId}的评分:${ratingId}`);

  // 模拟成功响应
  return { code: 200, message: "删除评分成功" };
};

const router = useRouter();
const userStore = useUserStore();

// 状态变量
const loading = ref(true);
const ratingList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);

// 编辑评分相关变量
const showEditDialog = ref(false);
const currentRating = ref(null);
const editForm = ref({
  score: 0,
  comment: "",
});

// 获取用户ID
const userId = computed(() => userStore.userId);

// 格式化日期
const formatDate = (dateStr) => {
  const date = new Date(dateStr);
  const today = new Date();
  const yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);

  if (date.toDateString() === today.toDateString()) {
    return "今天";
  } else if (date.toDateString() === yesterday.toDateString()) {
    return "昨天";
  } else {
    return `${date.getMonth() + 1}月${date.getDate()}日`;
  }
};

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return "";
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const hours = date.getHours().toString().padStart(2, "0");
  const minutes = date.getMinutes().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 获取项目类型名称
const getItemTypeName = (type) => {
  switch (type) {
    case "recipe":
      return "食谱";
    case "food":
      return "食材";
    default:
      return "未知类型";
  }
};

// 按日期分组
const groupedRatingList = computed(() => {
  const groups = {};

  ratingList.value.forEach((item) => {
    const date = new Date(item.rateTime).toDateString();
    if (!groups[date]) {
      groups[date] = [];
    }
    groups[date].push(item);
  });

  return groups;
});

// 加载评分记录
const loadRatings = async (refresh = false) => {
  if (refresh) {
    currentPage.value = 1;
    ratingList.value = [];
    hasMore.value = true;
  }

  if (!hasMore.value) return;

  try {
    loading.value = true;
    const res = await getUserRatings(
      userId.value,
      currentPage.value,
      pageSize.value
    );

    if (res.code === 200 && res.data) {
      if (res.data.records && res.data.records.length > 0) {
        ratingList.value.push(...res.data.records);
        currentPage.value++;

        // 检查是否还有更多数据
        hasMore.value = ratingList.value.length < res.data.total;
      } else {
        hasMore.value = false;
      }
    } else {
      showToast("获取评分记录失败");
      hasMore.value = false;
    }
  } catch (error) {
    console.error("加载评分记录失败", error);
    showToast("获取评分记录失败");
  } finally {
    loading.value = false;
  }
};

// 加载更多
const loadMore = () => {
  loadRatings();
};

// 编辑评分
const handleEditRating = (item) => {
  currentRating.value = item;
  editForm.value.score = item.score;
  editForm.value.comment = item.comment || "";
  showEditDialog.value = true;
};

// 确认编辑评分
const confirmEditRating = async () => {
  if (!currentRating.value) return;

  try {
    const res = await updateRating(
      currentRating.value.id,
      {
        score: editForm.value.score,
        comment: editForm.value.comment,
      },
      userId.value
    );

    if (res.code === 200) {
      showToast("更新评分成功");

      // 更新列表中的数据
      const index = ratingList.value.findIndex(
        (item) => item.id === currentRating.value.id
      );
      if (index !== -1) {
        ratingList.value[index].score = editForm.value.score;
        ratingList.value[index].comment = editForm.value.comment;
      }
    } else {
      showToast("更新评分失败");
    }
  } catch (error) {
    console.error("更新评分失败", error);
    showToast("更新评分失败");
  }
};

// 删除评分
const handleDeleteRating = (id) => {
  showConfirmDialog({
    title: "删除评分",
    message: "确定要删除此评分记录吗？",
  })
    .then(async () => {
      try {
        const res = await deleteRating(id, userId.value);
        if (res.code === 200) {
          showToast("删除成功");
          ratingList.value = ratingList.value.filter((item) => item.id !== id);
        } else {
          showToast("删除失败");
        }
      } catch (error) {
        console.error("删除评分失败", error);
        showToast("删除失败");
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 滑动单元格关闭前的回调函数
const beforeClose = ({ position, instance }) => {
  switch (position) {
    case "right":
      instance.close();
      break;
  }
};

// 导航到详情页
const navigateToDetail = (item) => {
  if (!item.type || !item.targetId) return;

  switch (item.type) {
    case "recipe":
      router.push(`/recipe/${item.targetId}`);
      break;
    case "food":
      router.push(`/food/${item.targetId}`);
      break;
    default:
      break;
  }
};

onMounted(() => {
  loadRatings(true);
});
</script>

<style scoped>
.ratings {
  padding-top: 46px;
  min-height: 100vh;
  background-color: #f7f8fa;
}

.content {
  padding: 16px;
}

.item-title {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.item-rating {
  display: flex;
  align-items: center;
}

.score-text {
  margin-left: 5px;
  font-size: 12px;
  color: #f44;
  font-weight: bold;
}

.item-type {
  font-size: 12px;
  color: #969799;
  background-color: #f2f3f5;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
  margin-top: 4px;
}

.item-comment {
  margin-top: 4px;
  font-size: 12px;
  color: #646566;
}

.rate-time {
  font-size: 12px;
  color: #969799;
  margin-top: 4px;
}

.edit-button {
  height: 100%;
  background-color: #1989fa;
}

.delete-button {
  height: 100%;
}

.load-more {
  text-align: center;
  margin-top: 20px;
}

.edit-rating-form {
  padding: 16px;
}

.edit-item-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 16px;
}

.edit-item-name {
  margin-top: 8px;
  font-size: 16px;
  font-weight: 500;
}

.edit-score {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.edit-label {
  width: 50px;
  font-size: 14px;
}

.edit-score-text {
  margin-left: 8px;
  font-size: 16px;
  color: #f44;
  font-weight: bold;
}

.edit-comment {
  margin-bottom: 16px;
}
</style>
